package com.Sdebruijn.curriculumvitae.util;

import java.io.File;

import android.content.Context;
import android.os.Environment;

/**
 * Utility class to get info about local storage.
 */
public final class StorageUtil {

	/**
	 * This class could not be instantiated.
	 */
	private StorageUtil() {
	}

	/**
	 * Get best cache path.
	 * 
	 * @param context
	 *            The current context of the app
	 * @return Will return getExternalCacheDir() if exists or getCacheDir() if
	 *         it doesn't
	 */
	public static String getBestCachePath(final Context context) {

		File cacheDir = null;

		if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.ECLAIR_MR1) {
			cacheDir = VersionHelper.getCacheDir(context);
		}

		if (cacheDir == null) {
			if (Environment.getExternalStorageState().equalsIgnoreCase(
					Environment.MEDIA_MOUNTED)) {
				cacheDir = new File(Environment.getExternalStorageDirectory()
						+ "/" + context.getApplicationInfo().name);
			} else {
				cacheDir = context.getCacheDir();
			}
		}

		return cacheDir.getPath();
	}

	/**
	 * This is a workaround for VerifyError error that is thrown when a method
	 * is not found on the device sdk. This can happen if an app is run on a
	 * device running Android version < 7.
	 * 
	 */
	static final class VersionHelper {

		/**
		 * If external storage is mounted with read/write access return the
		 * ExternalCacheDir, if not return the internal cache dir.
		 * 
		 * @param context
		 *            the context
		 * @return the cache dir
		 */
		static File getCacheDir(final Context context) {
			File cacheDir = null;
			if (Environment.getExternalStorageState().equalsIgnoreCase(
					Environment.MEDIA_MOUNTED)) {
				cacheDir = context.getExternalCacheDir();
			}

			if (cacheDir == null) {
				cacheDir = context.getCacheDir();
			}

			return cacheDir;
		}
	}
}
